import axios from "axios";
import { generateSignature,getDate } from "./ai";
const APPID='3399720a';
const API_KEY = '20f0551e82d1528ed188fbf7048d3c0c';
const API_SECRET = 'YmUwZDI5MDIzNTMyMzg1NmYyZTY5OGU0';
const HOST='iat-api.xfyun.cn';

export const recognizeSpeech=async(audioBlob:Blob)=>{
    const date=getDate();
    const signature=generateSignature(API_KEY,API_SECRET,date);
    const url=`https://${HOST}/v2/iat`;
    const reader=new FileReader();
    reader.readAsDataURL(audioBlob);
    return new Promise<string | null>((resolve,reject)=>{
        reader.onload=async()=>{
            const base64Audio=(reader.result as string).split(',')[1];
            try{
                const response=await axios.post(url,{
                    common:{
                        app_id:APPID
                    },
                    business:{
                        language:'zh_cn',
                        domain:'iat',
                        accent:'mandarin'
                    },
                    data:{
                        status:2,
                        format:'wav',
                        encoding:'raw',
                        audio:base64Audio
                    }
                },{
                    headers:{
                      'Content-Type':'application/json',
                      'Host':HOST,
                      'Date':date,
                      'Authorization':signature
                    }
                
                });
                //这里需要根据科大讯飞实际返回的数据结构解析识别结果
                if(response.data.code===0){
                    const result=response.data.data.result.ws.map((item:any)=>item.cw[0].w).join('');
                    resolve(result);
                }
                else{
                    console.error('语音识别出错',response.data.message);
                    resolve(null);
                }
            }catch(error){
                console.error('语音识别出错',error);
                reject(error);
            }
        }
    })
}